package com.jblv.frame.config.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriTemplate;

import java.net.URI;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ConfigBootstrapHttpUtils
 * @projectName jblv-frame
 * @packageName com.jblv.frame.config.utils
 * @description TODO
 * @date Create at 2020/9/7 17:06
 * @since jdk1.8
 */
public class ConfigBootstrapHttpUtils {
    private final static Logger logger = LoggerFactory.getLogger(ConfigBootstrapHttpUtils.class);

    private static String uri = ConfigBootstrapProperties.getUri().trim();

    private static String host = ConfigBootstrapProperties.getHost().trim();

    public static JSONObject getConfig() {
        String[] arrayOfString = { uri, host };
        String url = "{uri}/config/{host}/jblv-config";
        return httpGet(url, arrayOfString);
    }

    public static JSONObject getAllConfig() {
        String[] arrayOfString = { uri };
        String url = "{uri}/config/jblv-config";
        return httpGet(url, arrayOfString);
    }

    public static JSONObject getSystemConfig() {
        String[] arrayOfString = { uri };
        String url = "{uri}/config/system/jblv-config";
        return httpGet(url, arrayOfString);
    }

    public static JSONObject getSoftwareConfig() {
        String[] arrayOfString = { uri, host };
        String url = "{uri}/config/{host}/software";
        return httpGet(url, arrayOfString);
    }

    public static JSONObject getAllSoftwareConfig() {
        String[] arrayOfString = { uri };
        String url = "{uri}/config/software";
        return httpGet(url, arrayOfString);
    }

    private static JSONObject httpGet(String url, Object[] args) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            URI expanded = (new UriTemplate(url)).expand(args);
            if (logger.isInfoEnabled()) {
                logger.info("Fetching config from server at: " + expanded.toString());
            }
            httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(expanded.toString());
            RequestConfig.Builder builder = RequestConfig.custom();
            builder.setConnectTimeout(5000);
            builder.setConnectionRequestTimeout(1000);
            builder.setSocketTimeout(5000);
            RequestConfig requestConfig = builder.build();
            get.setConfig(requestConfig);
            response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.error("Fetching config from server at: " + url + " failed.");
                return null;
            }
            HttpEntity respEntity = response.getEntity();
            if (respEntity == null) {
                logger.debug("httpclient respEntity is null");
                return null;
            }
            String content = EntityUtils.toString(respEntity, "UTF-8");
            if (StringUtils.isBlank(content)) {
                logger.debug("httpclient response is null or empty");
                return null;
            }
            return JSONObject.parseObject(content);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}
